/**
 * 开票
 */

/**
 * 验收
 */
'use strict';
import React from 'react';
import {connect} from 'dva/index';
import {
  Button, Card,
  Col,
  DatePicker,
  Drawer,
  Dropdown,
  Form,
  Input,
  Modal,
  Popconfirm,
  Row,
  Select, Statistic,
  Table,
  Tabs
} from 'antd';
import FormBase from '../../components/Base/FormBase';
import moment from 'moment';
import 'moment/locale/zh-cn';
import styles from "../index.less";
import ViewTitle from "../../components/ViewTitle";
import {FormField, ModalView, SearchForm} from "antd-extra";
import ModalCreateOrEditInvoiceRecord from "./modal/ModalCreateOrEditInvoiceRecord";
import finance from "../../models/finance";
import ModalSalesOrderDetail from "../sales/modal/ModalSalesOrderDetail";
import Icon from "antd/es/icon";

moment.locale('zh-cn');
const {RangePicker} = DatePicker;
const _ = require('lodash');
const {Option} = Select;
const table = 'ProcureOrder';
const title = '开票';
const type = 'invoicing';
const {TabPane} = Tabs;
@Form.create()
@connect(({
            user,
            global,
            dict,
            finance
          }) => ({...user, ...global, ...finance, ...dict}))
export default class Invoicing extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {dispatch} = this.props;
    const payload = this.props.form.getFieldsValue();

    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });
    payload['type'] = type;
    dispatch && dispatch({
      type: 'finance/findInvoiceRecords',
      payload
    });
    this.props.dispatch({
      type: 'dict/findMany',
      payload: {type: 'division'}
    });
    this.props.dispatch({
      type: 'finance/findInvoiceSalesMany',
      payload
    });
    this.props.dispatch({
      type: 'finance/invoiceAssess',
      payload
    });
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table: 'SalesOrder'}
    });
  }

  cols() {
    return [
      {
        title: "客户名称", dataIndex: 'name', key: 'name', render: (value, record) => {
          const {name, code} = record;
          return this.getProductionElement(code, name);
        }
      },

      {title: "开票公司", dataIndex: 'division', key: 'division'},
      {title: "开票金额", dataIndex: 'amount', key: 'amount'},
      {title: "税率", dataIndex: 'taxRate', key: 'taxRate'},
      {title: "发票号", dataIndex: 'invoiceNumber', key: 'invoiceNumber'},

      {
        title: "开票时间", dataIndex: 'createdTs', key: 'createdTs', render: value => {
          return <div>{moment(value).format('YYYY-MM-DD HH:mm:ss')}</div>;
        }
      },
      {
        title: '操作', dataIndex: 'operation', key: 'operation',
        width: 160,
        render: (value, record) => {
          return (
            <span>
              {<a style={{marginRight: '6px'}} onClick={() => {
                this.onCreateOrEdit(record);
              }}>编辑</a>
              }
              {<Popconfirm
                title="确认删除"
                onConfirm={() => {
                  this.props.dispatch({
                    type: 'finance/deleteInvoiceRecord',
                    payload: record
                  }).then(res => {
                    this.requestReturn(res);
                    this.componentDidMount();
                  });
                }}
                okText="是"
                cancelText="否"
              >
                <a style={{marginRight: '6px'}}>删除</a>
              </Popconfirm>}
            </span>
          );
        }
      }
    ];
  }

  getSearchFields = () => {
    const {divisionDict} = this.props;
    return [
      <FormField
        label="客户名称"
        name="name"
        key={1}
      >
        <Input allowClear placeholder={`请输入客户名称`}/>
      </FormField>,
      <FormField
        label={'销售公司'}
        name={`division`}
        key={`division`}
      >
        <Select allowClear placeholder={`请输入${title}`}>{this.getDivision(divisionDict)}</Select>
      </FormField>,
      <FormField
        label={`统计时间`}
        name="createdTs"
        key={3}
        initialValue={[this.getSearchStart1Months(), this.getDefaultSearchEndDate()]}
      >
        <RangePicker allowClear={true}
          // style={{ width: '150%' }}
        />
      </FormField>
    ];
  };
  onCreateOrEdit = (record) => {
    const _type = record ? 'finance/updateInvoiceRecord' : 'finance/createInvoiceRecord';
    ModalView.open(ModalCreateOrEditInvoiceRecord, {
      title: record ? "编辑" : "添加",
      width: '1080px'
    }, {
      record,
      callback: (payload) => {
        payload.type = type;
        this.props.dispatch({
          type: _type,
          payload
        }).then(res => {
          this.requestReturn(res);
          this.componentDidMount();
        });
      }

    });
  };
  getTableCols = () => {
    const model = this.props[`SalesOrderModel`];
    const temp = [];
    temp.push({
      title: '采购单价状态', dataIndex: 'priceStatus', key: 'priceStatus', render: (value, record) => {
        const {prods = []} = record;
        let isOk = true;
        _.map(prods, prod => {
          const {materials} = prod;
          _.map(materials, material => {
            const {price = 0} = material;
            if (price === 0) isOk = false;
          });
        });
        return isOk ? <div style={{color: "#2b2"}}>OK</div> : <div style={{color: "#f22"}}>待补充</div>;
      }
    });
    temp.push(...this.getTableColumns(model));
    _.remove(temp, item => item.dataIndex === 'rentStartDate');
    _.remove(temp, item => item.dataIndex === 'rentEndDate');
    _.remove(temp, item => item.dataIndex === 'rentReturnDate');
    temp.push(
      {
        title: '操作', dataIndex: 'operation', key: 'operation',
        width: 160, fixed: 'right',
        render: (value, record) => {
          return (
            <span>
           {<a style={{marginRight: '6px'}}
               onClick={() => this.setState({showDetail: true, record})}>详情</a>}
            </span>
          );
        }
      });
    return temp;

  };

  render() {
    const {form, invoicingRecords = [], salesInvoices = [], invoiceAssess = {}} = this.props;
    const {salesInvoiceTotal = 0, invoicingTotal = 0} = invoiceAssess;
    console.log('salesInvoices', salesInvoices);
    const {record = {}, showDetail} = this.state;
    return <Form className={styles.content}>
      <ViewTitle
        title={`开票统计`}
        level={1}

      ></ViewTitle>
      <SearchForm
        style={{marginLeft: '6px', marginRight: '6px'}}
        onSearch={() => {
          this.state.current = 1;
          this.componentDidMount();
        }}
        onReset={this.handleReset}
        cols={3}
        min={6}
        expandText="展开"
        form={form}
      >
        {this.getSearchFields()}
      </SearchForm>
      <div style={{background: '#ECECEC', padding: '30px'}}>
        <Row gutter={16}>
          <Col span={8}>
            <Card>
              <Statistic
                title="需开票订单总金额"
                value={salesInvoiceTotal}
                precision={2}
                valueStyle={{color: '#3f8600'}}
                suffix="元"
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <Statistic
                title="已开票总金额"
                value={invoicingTotal}
                precision={2}
                valueStyle={{color: '#2222ff'}}
                suffix="元"
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <Statistic
                title="未开票总金额"
                value={salesInvoiceTotal - invoicingTotal}
                precision={2}
                valueStyle={{color: '#cf1322'}}
                suffix="元"
              />
            </Card>
          </Col>
        </Row>
      </div>
      <Tabs defaultActiveKey="1">
        <TabPane tab="已开票" key="1">
          <ViewTitle
            title={`${title}记录列表`}
            level={1}
            actions={<Button type={'primary'} onClick={() => this.onCreateOrEdit()}>添加</Button>}
          ></ViewTitle>

          <Table
            className={styles.antTable}
            bordered={true}
            columns={this.cols()}
            dataSource={invoicingRecords}
            // scroll={{ x: true }}
            pagination={true}
          ></Table>
        </TabPane>
        <TabPane tab="需开票" key="2">
          <ViewTitle
            title={`需开票订单记录列表`}
            level={1}
          ></ViewTitle>
          <Table
            className={styles.antTable}
            bordered={true}
            columns={this.getTableCols()}
            dataSource={salesInvoices}
            scroll={{x: true}}
            pagination={{
              current: this.state.current,
              total: this.state.total,
              showSizeChanger: true,
              onChange: page => {
                this.state.current = page;
                this.componentDidMount();
              },
              onShowSizeChange: (current, pageSize) => {
                this.state.current = 1;
                this.state.pageSize = pageSize;
                this.componentDidMount();
              }
            }}
            //  scroll={{ x: 1300 }}
          ></Table>

          {showDetail && <Drawer
            visible={showDetail}
            title={`${title}详情`}
            placement="left"
            width={'80%'}
            style={{padding: 0}}
            // maskClosable={false}
            onClose={() => {
              this.setState({showDetail: false});
              this.componentDidMount();
            }}
          >
            <ModalSalesOrderDetail
              values={record}
            > </ModalSalesOrderDetail>
          </Drawer>}
        </TabPane>

      </Tabs>

    </Form>;
  }
}

